package br.edu.unilasalle.simon_api.dao.impl;

import java.util.List;

import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;

import br.edu.unilasalle.simon_api.dao.ICondPagtoDao;
import br.edu.unilasalle.simon_api.domain.CondicaoPagamento;

@Repository
public class CondPagtoDao extends GenericDao<CondicaoPagamento, Long> implements ICondPagtoDao {
	
	public List<CondicaoPagamento> findAllCondPagto() {
        StringBuilder str = new StringBuilder();
        str.append("select new CondicaoPagamento(o.id, o.parcelas, o.valorMinimo, o.diasVencimento, ");
        str.append("o.formaPagamento.id, o.formaPagamento.descricao) from CondicaoPagamento o ");
        str.append("order by o.formaPagamento.id, o.parcelas");
        TypedQuery<CondicaoPagamento> q = entityManager.createQuery(str.toString(), CondicaoPagamento.class);
		return q.getResultList();
    }
	
	public Integer findDiasVencimento(Long idFormPagto, Integer parcelas) {
        StringBuilder str = new StringBuilder();
        str.append("select o.diasVencimento from CondicaoPagamento o ");
        str.append("where o.formaPagamento.id = :idFormPagto and o.parcelas = :parcelas");
        Query q = entityManager.createQuery(str.toString());
        q.setParameter("idFormPagto", idFormPagto);
        q.setParameter("parcelas", parcelas);
        try {
        	return (Integer) q.getSingleResult();
        } catch (NoResultException e) {
        	return null;
        }
    }
	
	public Boolean findByValor(Double valor, Long idFormPagto, Integer parcelas) {
		StringBuilder str = new StringBuilder();
        str.append("select o.id from CondicaoPagamento o where :valor >= o.valorMinimo and ");
        str.append("o.formaPagamento.id = :idFormPagto and o.parcelas = :parcelas");
        Query q = entityManager.createQuery(str.toString());
        q.setParameter("valor", valor);
        q.setParameter("idFormPagto", idFormPagto);
        q.setParameter("parcelas", parcelas);
        try {
        	q.getSingleResult();
        	return Boolean.TRUE;
        } catch (NoResultException e) {
        	return Boolean.FALSE;
        }
	}
	
}
